﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.WareHoustForm;
using BW.Mes.WinForms.BasicData;

namespace BW.Mes.WinForms.BasicData
{
   
    public partial class WorkshopForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _workshopApiBaseUrl = "https://localhost:7274";
        private List<WorkShopModel> _allWorkshops = new List<WorkShopModel>(); // 保存所有数据

        public WorkshopForm()
        {
            InitializeComponent();
            //初始化httpClient, 忽略SSL证书验证
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
            };
            _httpClient = new HttpClient(handler);
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 窗体加载时获取数据
            this.Load += WorkshopForm_Load;
            // 设置序号列为自增
            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
            gridView1.CustomColumnDisplayText += gridView1_CustomColumnDisplayText;

            // 支持多选和复选框列
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
        }
        private async void WorkshopForm_Load(object sender, EventArgs e)
        {
            await LoadWorkshopData();
        }
        // 加载仓库数据
        private async Task LoadWorkshopData()
        {
            try
            {
                var workshop = await GetApiDataAsync<List<WorkShopModel>>("api/Workshop/GetWorkshop");
                _allWorkshops = workshop ?? new List<WorkShopModel>();
                gridControl1.DataSource = null;
                gridControl1.DataSource = _allWorkshops;
                gridView1.PopulateColumns();
                // 隐藏Id列
                var idColumn = gridView1.Columns["Id"];
                if (idColumn != null) idColumn.Visible = false;
                EnsureSerialNumberColumn();
                gridView1.BestFitColumns();
                gridView1.RefreshData();
            }
            catch (Exception ex)
            {
                var errorMessage = $"加载数据失败: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMessage += $"\n内部错误: {ex.InnerException.Message}";
                }
                errorMessage += $"\n\n请确保后端服务正在运行，并且地址 {_workshopApiBaseUrl} 正确无误。";
                MessageBox.Show(errorMessage, "错误");
            }
        }
        /// <summary>
        /// 获取车间
        /// </summary>
        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_workshopApiBaseUrl}/{endpoint}");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                // 调试显示原始响应内容
                Console.WriteLine($"API响应: {responseBody}");

                // 先解析为JObject以便提取内部数据
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                // 假设数组数据在"data"字段中
                if (jsonObject["pageDatas"] != null)
                {
                    string dataJson = jsonObject["pageDatas"].ToString();
                    Console.WriteLine($"提取的pageDatas字段: {dataJson}");

                    return JsonConvert.DeserializeObject<T>(dataJson);
                }

                return JsonConvert.DeserializeObject<T>(responseBody);
            }
            catch (Exception ex)
            {
                var errorMessage = $"获取数据失败: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMessage += $"\n内部错误: {ex.InnerException.Message}";
                }
                errorMessage += $"\n\n请确保后端服务正在运行，并且地址 {_workshopApiBaseUrl} 正确无误。";
                MessageBox.Show(errorMessage, "错误");
                return default;
            }
        }
        // 提交数据到API
        public async Task<bool> PostApiDataAsync<T>(string endpoint, T data)
        {
            try
            {
                string jsonData = JsonConvert.SerializeObject(data);
                HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.PostAsync($"{_workshopApiBaseUrl}/{endpoint}", content);
                response.EnsureSuccessStatusCode();
                return true;
            }
            catch (Exception ex)
            {
                var errorMessage = $"提交数据失败: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMessage += $"\n内部错误: {ex.InnerException.Message}";
                }
                errorMessage += $"\n\n请确保后端服务正在运行，并且地址 {_workshopApiBaseUrl} 正确无误。";
                XtraMessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        public class WorkShopModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 车间名称
            /// </summary>
            [DisplayName("车间编号")]
            public string WorkshopCode { get; set; }
            // 车间编号
            [DisplayName("车间名称")]
            public string WorkshopName { get; set; }
            // 车间描述
            [DisplayName("车间描述")]
            public string WorkshopMsg { get; set; }
            [DisplayName("创建人")]
            public string CreatedBy { get; set; }
            [DisplayName("更新时间")]
            public DateTime CreatedAt { get; set; } = DateTime.Now;
            [DisplayName("修改时间")]
            public DateTime? UpdatedAt { get; set; }
        }

        

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            LoadWorkshopData();
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            var addForm = new AddWorkshopForm();
            if (addForm.ShowDialog() == DialogResult.OK)
            {
                // 添加成功后刷新数据
                LoadWorkshopData();
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadWorkshopData();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string code = textEditCode.Text.Trim();
            string name = textEditName.Text.Trim();
            var filtered = _allWorkshops.Where(w =>
                (string.IsNullOrEmpty(code) || (w.WorkshopCode != null && w.WorkshopCode.Contains(code))) &&
                (string.IsNullOrEmpty(name) || (w.WorkshopName != null && w.WorkshopName.Contains(name)))
            ).ToList();
            gridControl1.DataSource = null;
            gridControl1.DataSource = filtered;
            gridView1.PopulateColumns();
            // 隐藏Id列
            var idColumn = gridView1.Columns["Id"];
            if (idColumn != null) idColumn.Visible = false;
            EnsureSerialNumberColumn();
            gridView1.BestFitColumns();
            gridView1.RefreshData();
        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.ListSourceRowIndex >= 0)
            {
                e.DisplayText = (e.ListSourceRowIndex + 1).ToString();
            }
        }

        private void EnsureSerialNumberColumn()
        {
            if (gridView1.Columns["序号"] == null)
            {
                var col = gridView1.Columns.AddField("序号");
                col.Caption = "序号";
                col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                col.Visible = true;
                col.VisibleIndex = 0;
            }
            else
            {
                gridView1.Columns["序号"].Visible = true;
                gridView1.Columns["序号"].VisibleIndex = 0;
            }
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.IsGetData)
            {
                e.Value = e.ListSourceRowIndex + 1;
            }
        }

        private async void btnDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的车间！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var confirm = XtraMessageBox.Show($"确定要删除选中的 {selectedRows.Length} 个车间吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;

            foreach (var rowHandle in selectedRows)
            {
                var workshop = gridView1.GetRow(rowHandle) as WorkShopModel;
                if (workshop != null)
                {
                    await DeleteWorkshop(workshop.Id);
                }
            }
            await LoadWorkshopData();
        }

        private async Task DeleteWorkshop(long id)
        {
            try
            {
                var response = await _httpClient.PutAsync($"{_workshopApiBaseUrl}/api/Workshop/DeleteWorkshop?id={id}", null);
                var responseContent = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    // 可根据API返回内容进一步处理
                    var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                    if (apiResult != null && apiResult.success == 1)
                    {
                        // 删除成功
                    }
                    else
                    {
                        string errorMessage = apiResult?.message ?? "删除失败，未知错误";
                        XtraMessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    string errorMessage = $"HTTP错误：{response.StatusCode}";
                    try
                    {
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (apiResult != null && !string.IsNullOrEmpty(apiResult.message))
                        {
                            errorMessage = apiResult.message;
                        }
                    }
                    catch { }
                    XtraMessageBox.Show($"删除失败：{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除异常: {ex.Message}", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length != 1)
            {
                XtraMessageBox.Show("请只选择一条要修改的数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var workshop = gridView1.GetRow(selectedRows[0]) as WorkShopModel;
            if (workshop == null)
            {
                XtraMessageBox.Show("未获取到车间信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var updateForm = new UpdateWorkshopForm(workshop);
            if (updateForm.ShowDialog() == DialogResult.OK)
            {
                LoadWorkshopData();
            }
        }
    }
}